package controllers;

import helpers.NumberHelper;
import helpers.UrlHelper;

import java.io.IOException;
import java.util.TreeMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

public class CheckSpeedServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		
		TreeMap<String, String> check = new TreeMap<String, String>();
		String name = (String) request.getParameter("domain");
		
		String loadtime = "";
		String pagesize = "";
		String average = "";
		
		if (name != null && !UrlHelper.checkDomain(name)) {
			check.put("name", "Please input a valid domain.");
		} else if (name != null) {
			name = UrlHelper.getMainDomain(name);
		} 
		
		
		if (name != null && check.size() == 0) {
			try {
				Long start = System.nanoTime();
				String url = "";
				if (UrlHelper.checkIsSubDomain(name)) {
					url = "http://" + name;
				} else {
					url = "http://www." + name;
				}
				Document doc = Jsoup.connect(url).get();
				Long end = System.nanoTime();
				long elapsedTime = end - start;
				double second = (double) elapsedTime / 1000000000.0;
				loadtime = Double.toString(second);
				
				long size = Long.parseLong(Integer.toString(doc.html().getBytes().length));
				pagesize = NumberHelper.readableFileSize(size);
				
				if (second != 0) {
					double averg = second/size;
					average = NumberHelper.numberFormat(averg);
				}
				
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
		//Cache header
		response.addHeader("Cache-Control", "public, max-age=60000");
		
		request.setAttribute("check", check);
		request.setAttribute("name", name);
		request.setAttribute("loadtime", loadtime);
		request.setAttribute("pagesize", pagesize);
		request.setAttribute("average", average);
		try {
			request.getRequestDispatcher("/pages/check_speed.jsp").forward(request, response);
		} catch (ServletException e) {
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args) {
		double db = 3.1231934714302344E-5;
		
		System.out.println(String.format("%10.5f", db));
	}
}
